<template>
    <div id="winRegist">
        <!-- 面包屑 -->
        <el-breadcrumb :separator-icon="ArrowRight" style="margin-bottom: 10px;">
            <!-- <el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item> -->
            <el-breadcrumb-item>挂号收费</el-breadcrumb-item>
            <el-breadcrumb-item>窗口挂号</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="card-header">
            <el-button class="button" type="primary" :icon="Plus" style="padding-left: 0.5%;"
                @click="addRegist">挂号</el-button>
            <el-button class="button" type="primary" :icon="Plus" style="padding-left: 0.5%;"
                @click="checkAll">显示form</el-button>
        </div>

        <p v-if="emptyShow != ''" style="color: red;">请补全以下内容：{{ emptyShow }}</p>

        <h2 style="margin: 10px;">基本信息</h2>


        <el-card class="base-card" shadow="always">
            <el-form :model="form" label-width="80px">
                <div class="base-d1">
                    <el-form-item label="病历号" class="base-d11">
                        <el-input v-model="form.caseNum"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" class="base-d12">
                        <el-input v-model="form.name"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" class="base-d13">
                        <el-input v-model="form.sex"></el-input>
                    </el-form-item>
                </div>
                <div class="base-d1">
                    <el-form-item label="身份证号" class="base-d11">
                        <el-input v-model="form.idnum" @blur="calculateAge"></el-input>
                    </el-form-item>
                    <el-form-item label="出生日期" class="base-d11">
                        <div class="block">
                            <!-- <span class="demonstration">date</span> -->
                            <el-date-picker v-model="form.birthday" type="date" placeholder="Pick a date" disabled
                                value-format="YYYY-MM-DD" />
                        </div>

                    </el-form-item>
                    <el-form-item label="年龄" class="base-d11">
                        <el-input v-model="ageShow" disabled></el-input>
                    </el-form-item>

                </div>
                <div class="base-d1">
                    <el-form-item label="家庭住址" class="base-d11">
                        <el-input v-model="form.address"></el-input>
                    </el-form-item>
                    <el-form-item label="既往史" class="base-d11">
                        <el-input v-model="form.medicalhistory"></el-input>
                    </el-form-item>
                </div>
            </el-form>
        </el-card>

        <h2 style="margin: 10px;">挂号信息</h2>

        <el-card class="base-card" shadow="always">
            <el-form :model="form" label-width="80px" class="base-card">
                <div class="base-d1">
                    <el-form-item label="看诊日期" class="base-d11">
                        <div class="block">
                            <!-- <span class="demonstration">date</span> -->
                            <el-date-picker v-model="form.visitDate" type="date" placeholder="Pick a date"
                                @change="visit_set" @blur="visit_set" value-format="YYYY-MM-DD" />



                        </div>

                    </el-form-item>
                    <el-form-item label="星期" class="base-d12">
                        <el-input v-model="weekday_string" disabled></el-input><!--切换为不可更改-->
                    </el-form-item>
                    <el-form-item label="午别" class="base-d13">
                        <!--切换为下拉框-->
                        <el-select v-model="form.noon" class="m-2" value-key="value" style="width: 100px">
                            <el-option v-for="item in selectnoon" :key="item.value" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="base-d1">
                    <el-form-item label="挂号科室" class="base-d11">
                        <el-select v-model="form.deptId" class="m-2" value-key="value" style="width: 100px"
                            placeholder="请选择">
                            <el-option v-for="item in selectdept" :key="item.value" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="号别" class="base-d11">
                        <el-select v-model="form.leve_id" class="m-2" value-key="value" style="width: 100px"
                            placeholder="请选择">
                            <el-option v-for="item in optionLevels" :key="item.id" :label="item.levelName"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="看诊医生" class="base-d11">

                        <el-select 
                        @click="LoadDoc" 
                        @change="calculateMoney" 
                        v-model="doctor_id" 
                        class="m-2" 
                        value-key="id"
                        style="width: 200px" 
                        placeholder="请选择">
                            <el-option v-for="item in optionDoc" :key="item.id"
                                :label="' ' + item.name + ' (剩余挂号：' + (item.patientnum - item.worknum) + ' 个)'"
                                :value="item.id"
                                :disabled="(item.patientnum - item.worknum) ==0"
                                ></el-option>
                        </el-select>
                    </el-form-item>

                </div>
                <div class="base-d1">
                    <el-form-item label="初始号额" class="base-d11">
                        <el-input disabled v-model="AllNum"></el-input> <!--切换为不可输入-->
                    </el-form-item>
                    <el-form-item label="已用号额" class="base-d11">
                        <el-input disabled v-model="useNum"></el-input> <!--切换为不可输入-->
                    </el-form-item>
                    <el-form-item label="病历本" class="base-d11">
                        <el-switch v-model="switch_state" class="mt-2" inline-prompt :active-icon="Check"
                            :inactive-icon="Close" style="margin-left: 24px;  --el-switch-off-color: #ff4949"
                            @click="switch_check" />
                    </el-form-item>

                </div>
                <div class="base-d1">
                    <el-form-item label="应收金额" class="base-d11">
                        <el-input v-model="form.money" disabled></el-input><!--切换为不可输入-->
                    </el-form-item>
                    <el-form-item label="收款方式" class="base-d11">
                        <el-input placeholder="医保卡" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="收款卡号" class="base-d11">
                        <el-input v-model="form.medicalcard"></el-input>
                    </el-form-item>
                </div>
            </el-form>
        </el-card>

    </div>
</template>
<script setup>
import { ArrowRight, Plus, Check, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ref } from 'vue';
import $axios from "../../utils/axios.js";

const form = ref({
    id: 1,
    caseNum: "233",
    name: "赵子鉴",
    sex: "男",
    idnum: "130604200212160916",
    birthday: new Date(2002, 11, 16),
    age: 21,
    address: "河北省保定市莲池区迎宾小区22号楼2单元301",
    medicalhistory: "无",

    visitDate: new Date(2002, 11, 16),
    weekday: "1",
    noon: "上午",

    deptId: 2,
    leve_id: 2,
    docId: -1,

    isBook: 1,//默认选择病历本
    money: 1,

    medicalcard: "10010",
    medicalmoney: "1",

})

const translations = {
    caseNum: "病历号",
    name: "姓名",
    sex: "性别",
    idnum: "身份证号",
    birthday: "出生日期",
    age: "年龄",
    address: "家庭住址",
    medicalhistory: "既往史",
    visitDate: "就诊日期",
    weekday: "星期",
    noon: "午别",
    deptId: "挂号科室",
    leve_id: "号别",
    docId: "看诊医生",
    // begine:"初始号额",
    // endnum:"已用号额",
    isBook: "病历本",
    money: "",
    medicalcard: "收款卡号",
    medicalmoney: "卡费用",
    delmark: 0,
};

const switch_state = ref(true)

const doctor = ref({
    id: '',
    name: '',
    deptid: '',
    levelId: '',
    worknum: '',
    patientnum: '',
    delmark: '',

})
const doctor_id = ref();
const AllNum = ref('');
const useNum = ref('');
const selectnoon = [{
    value: "上午",
    label: "上午"
}, {
    value: "下午",
    label: "下午"
}]
const selectdept = [
    {
        value: 1,
        label: "内科"
    }, {
        value: 2,
        label: "外科"
    }, {
        value: 3,
        label: "妇产科"
    }, {
        value: 4,
        label: "儿科"
    }, {
        value: 5,
        label: "眼科"
    }, {
        value: 6,
        label: "精神科"
    },
]
const optionDoc = ref([
    {
        id: '',
        name: "请选择",
        levelId: '',
        deptid: '',
        worknum: '',
        patientnum: '',
        delmark: '',
    }
])
const optionLevels = ref([
    {
        id: '',
        levelCode: '',
        levelName: '',
        levelFee: '',
        delmark: '',
    }
])
const emptyShow = ref('')

const weekday_string = ref()
const checkAll = () => {
    console.log("Checking");
    for (let i in form.value) {
        console.log(i, ":", form.value[i]);
    }

    console.log("doctor", doctor.value);
    console.log("optionDoc", optionDoc.value)
    console.log(FormatBirthday(form.value.birthday));
    console.log(form.value);



}
const switch_check = () => {

    form.value.isBook = switch_state.value ? 1 : 0;
    console.log(form.value.isBook);
    if(switch_state.value==1){
        console.log("+form.value.money:", form.value.money);
        form.value.money= form.value.money+1;
    }
    else{
        console.log("-form.value.money:", form.value.money);
        form.value.money= form.value.money-1;
    }

}

const addRegist = async () => {
    emptyShow.value = "";
    let is_empty=false;
    console.log("form:",form.value);
    for (let i in form.value) {

        if (form.value[i] === null || form.value[i] === ""||form.value[i]==-1
            ) {
            // console.log(i, "空");
            emptyShow.value = emptyShow.value + translations[i] + " ";
            console.log(typeof (form.value[i]));
                is_empty=true;
        }
        else {
            // console.log(i, ":", form.value[i]);
        }

    }
    if(is_empty){
        return;
    }
    //后端已经通过@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")注解把格式转换了

    // console.log("s1:", typeof (form.value.visitDate));
    // console.log("s12:", form.value.visitDate);
    // console.log("s2:", typeof (form.value.birthday));
    // console.log("s22:", form.value.birthday);
    // form.value.birthday = DateFormat(form.value.birthday);
    // form.value.visitDate = DateFormat(form.value.visitDate);
    // console.log("s31:", form.value.visitDate);
    // console.log("s32:", form.value.birthday);
    
    form.value.isBook = form.value.isBook ? 1 : 0;
    console.log("1:\n", typeof (form.value.isBook), form.value.isBook);
    console.log(form.value);
    const path = "/patient/add"
    const { data: res } = await $axios.put(
        path, form.value,
        {
            headers: {
                'Content-Type':
                    'application/json; charset=UTF-8' //将表单数据传递转化为form-data类型
            }
        }).then().catch((err) => { console.log("错啦", err); })
    form.value.isBook = form.value.isBook === 1 ? true : false
    console.log("res", res);
    open_success()
    form.value={
        id: 1,
        caseNum: "",
        name: "",
        sex: "",
        idnum: "",
        birthday: '',
        age: '',
        address: "",
        medicalhistory: "无",

        visitDate: '',
        weekday: "",
        noon: "",

        deptId: '',
        leve_id: '',
        docId: '',

        isBook: 1,//默认选择病历本
        money: '',

        medicalcard: "",
        medicalmoney: "",
    }
    AllNum.value='';
    useNum.value='';
    doctor.value='';
    doctor_id.value='';
    ageShow.value='';
    weekday_string.value='';
}
const open_success = () => {
    ElMessage({
        showClose:true,
        message: '挂号成功',
        type: 'success',
        customClass:'message'
    })
}
// const NowDateFormat = () => {
//     var date = new Date()
//     var year = date.getFullYear()
//     var month = date.getMonth() + 1 < 10 ?
//         '0' + (date.getMonth() + 1) : date.getMonth() + 1
//     var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

//     var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
//     var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
//     var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
//     const a = + hours + ':' + minutes + ':' + seconds;
//     console.log(a);
//     return year + '-' + month + '-' + day + 'T';
// }
// function DateFormat(date) {

//     var year = date.getFullYear()
//     var month = date.getMonth() + 1 < 10 ?
//         '0' + (date.getMonth() + 1) : date.getMonth() + 1//为了在个位数月份前加上0
//     var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
//     var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
//     var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
//     var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
//     return year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
// }
const FormatBirthday = () => {
    var date = form.value.birthday;
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ?
        '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

    var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    return year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
}

const autoSet = async () => {
    // 病历号随机生成
    form.value.caseNum = Math.random().toString(36).substring(2, 15);
    // 从数据库自动获取号别，每一个号别对应的价格，以及病历本的价格
    const path = "/level/q/all";
    const { data: res } = await $axios.get(path)
    if (res.code === 200) {
        // 为号别下拉框提供选项, 储存号别对应价格
        optionLevels.value = res.result;
        console.log("level:",optionLevels.value);
    }
    //看诊日期默认设为当天
    const today = new Date();
    var year = parseInt(today.getFullYear());
    var month = today.getMonth() + 1 < 10 ? '0' + (today.getMonth() + 1) : today.getMonth() + 1
    var day = today.getDate() < 10 ? '0' + today.getDate() : today.getDate();
    form.value.visitDate = year + "-" + month + "-" + day;
    visit_set();
    console.log("autoSet is ok");
}
autoSet();
const visit_set = () => {


    // 看诊日期自动生成，为当天日期,自动计算出星期数
    console.log("already in visit_set：\n", form.value.visitDate);
    if (form.value.visitDate === null) {
        form.value.weekday = '';
        weekday_string.value = "";
        console.log("done this");
        return null;
    }

    form.value.weekday = new Date(form.value.visitDate).getDay() === 0 ? 7 : new Date(form.value.visitDate).getDay()
    switch(form.value.weekday){
        case 1:
            weekday_string.value='星期一'
            break;
        case 2:
            weekday_string.value = '星期二'
            break;
        case 3:
            weekday_string.value = '星期三'
            break;
        case 4:
            weekday_string.value = '星期四'
            break;
        case 5:
            weekday_string.value = '星期五'
            break;
        case 6:
            weekday_string.value = '星期六'
            break;
        case 7:
            weekday_string.value = '星期日'
            break;

    }
    // weekday_string.value = form.value.weekday;


}
visit_set();

const ageShow = ref(form.value.age + " 岁");
const calculateAge = () => {
    //130604 20021216 0916

    if (form.value.idnum.length < 18) {
        return null;
    } else {

        var year_bir = parseInt(form.value.idnum.substring(6, 10));
        var month_bir = parseInt(form.value.idnum.substring(10, 12));
        var day_bir = parseInt(form.value.idnum.substring(12, 14));

        // console.log(typeof (year_bir), year_bir);
        // console.log(typeof (year_bir + "-" + month_bir + "-" + day_bir), year_bir + "-" + month_bir + "-" + day_bir);
        // console.log(typeof (year + "-" + month + "-" + day), year + "-" + month + "-" + day);

        form.value.birthday = new Date(year_bir, month_bir - 1, day_bir).getTime();

        var bir = form.value.birthday

        form.value.birthday = year_bir + "-" + month_bir + "-" + day_bir;
        var now = new Date();
        var year_now = now.getFullYear();
        // var year_bir = bir.getFullYear();
        // console.log(now.getMonth());
        // console.log(year_bir);
        // console.log(year_now - year_bir);
        form.value.age = year_now - year_bir;
        if (year_now - year_bir > 0) {
            ageShow.value = (year_now - year_bir) + " 岁";
        }
        else if ((now.getMonth() - bir.getMonth()) > 0) {
            ageShow.value = (now.getMonth() - bir.getMonth()) + " 月";
        }
        else {
            ageShow.value = (now.getDate() - bir.getDate()) + " 天";
        }
    }
}
calculateAge()


const LoadDoc = async () => {
    form.value.docId = '';
    doctor.value = '';

    const d = {
        // visitDate:form.value.visitDate,
        weekday: form.value.weekday,
        noon: form.value.noon === "上午" ? 1 : 2,

        deptId: form.value.deptId,

        leve_id: form.value.leve_id,
    }
    console.log(d);
    const path = "/doc/q/see"
    const { data: res } = await $axios.post(
        path, d,
        {
            headers: {
                'Content-Type':
                    'application/json; charset=UTF-8' //将表单数据传递转化为form-data类型
            }
        })
    if (res.code == 200) {
        optionDoc.value = res.result;
        for (let i = 0; i < res.result.length; i++)
            console.log(res.result[i]);
    }


}


const calculateMoney = async(doc_option) => {
    
    for(let i in optionDoc.value){
        console.log("i: " + optionDoc.value[i].id);
        if(doc_option== optionDoc.value[i].id)
        {
            doctor.value= optionDoc.value[i];
            break;
        }
    }

    //完善病患的信息
    form.value.docId = doctor.value.id;
    console.log("doctor:", doctor.value);


    AllNum.value = doctor.value.patientnum;
    useNum.value=doctor.value.worknum;
    



    let money = form.value.isBook;
    console.log(form.value.isBook);
    console.log("book:",form.value.isBook);
    // if (form.value.isBook === 1) {
        
    //     money = money + 1;
    // }
    // console.log("doc_option:",doctor.value);

    console.log("optionLevels.value[doc_option.levelId]:", optionLevels.value[doctor.value.levelId - 1].levelFee);
    money+=optionLevels.value[doctor.value.levelId-1].levelFee;




    form.value.money = money ;
}
</script>


<style lang="scss">
.card-header {
    margin: 10px; //!!!更改细节
}
.message{
    background-color: red;
}
.base-card {
    width: 100%;
    height: 100%;

    .base-d1 {
        display: flex;
        // outline: 1px solid black;
        width: 100%;

        .base-d11 {
            flex: 1;
            align-items: center;
        }

        .base-d12 {
            flex: 1;
            align-items: center;
        }

        .base-d13 {
            flex: 1;
            align-items: center;
        }

        .base-s11 {
            margin-left: 10px;
            width: 80px;
            height: 20px;
        }

        .base-input {
            width: 50%
        }
    }

    .base-d2 {
        display: flex;
        // outline: 1px solid black;
        width: 100%;

        .base-d21 {
            flex: 1;
            align-items: center;
        }

        .base-d22 {
            flex: 1;
            align-items: center;
        }

        .base-d23 {
            flex: 1;
            align-items: center;
        }

        .base-s11 {
            margin-left: 10px;
            width: 80px;
            height: 20px;
        }

        .base-input {
            width: 50%
        }
    }

    .base-d3 {
        display: flex;
        // outline: 1px solid black;
        width: 100%;

        .base-d3-input {
            width: 400px;
        }
    }
}
</style>